package com.baseLearn.api.util;

import com.baseLearn.api.exception.ZjmsaOaException;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 *
 */
public class FileUtil {
    public static final String EMPTY = "";

    public static final String BLANK=" ";

    public static final String PERCENT="%";

    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    public static final String SLASH = "/";

    public static final String TRANSVERSE_LINE = "-";

    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /*
    表示doc xls ppt
     */
    private static final String DEPP = "depp";

    /*
    表示Microsoft 1997-2003格式下的doc xls ppt
     */
    public static final String KB = "KB";
    public static final String MB = "MB";
    public static final String ISO = "ISO8859-1";
    public static final String CONTRNT_TYPE = "multipart/form-data";
    public static final String MSIE = "MSIE";
    public static final String TRIDENT = "TRIDENT";
    public static final String EDGE = "EDGE";
    public static final String COMMA_SYMBOL = ",";
    public static final String CONTENT_DISPOSITION = "Content-Disposition";
    public static final String ATTACHMENT_FILENAME = "attachment;filename=";
    public static final String XLS = ".xls";
    /**
     * 创建目录，根据日期每天生成一个目录用来存放上传的文件
     *
     * @return 目录的名称
     */
    public static String createDir() {
        Calendar now = Calendar.getInstance();
        return now.get(Calendar.YEAR) + SLASH + (now.get(Calendar.MONTH) + 1) + SLASH + now.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 得到当前年
     *
     * @return
     */
    public static int getYear() {
        Calendar now = Calendar.getInstance();
        return now.get(Calendar.YEAR);
    }

    /**
     * 根据传入时间得到年份
     *
     * @return
     */
    public static int getYearByDate(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.YEAR);
    }


    /**
     * 为了保证文件名称不重复，采用uuid方式生成文件名
     *
     * @param originName 上传文件的名称
     * @return 新的文件名称
     */
    public static String createFileName(String originName) {

        return getUUID();
    }

    /**
     * 得到文件后缀
     *
     * @param originName
     * @return
     */
    public static String getFileSuffix(String originName) {
        int index = originName.lastIndexOf(".");
        if (index == -1) {
            throw new ZjmsaOaException("文件路径异常");
        }
        String suffix = originName.substring(index);
        return suffix;
    }






    /**
     * MultipartConfigFactory#parseSize()
     *
     * @param size
     * @return
     */
    public static long parseSize(String size) {
        Assert.hasLength(size, "Size must not be empty");
        size = size.toUpperCase();
        if (size.endsWith(KB)) {
            return Long.valueOf(size.substring(0, size.length() - 2)) * 1024;
        }
        if (size.endsWith(MB)) {
            return Long.valueOf(size.substring(0, size.length() - 2)) * 1024 * 1024;
        }
        return Long.valueOf(size);
    }

    /**
     * 字符串转date
     *
     * @param date yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date stringToDate(String date) {
        try {
            return dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String dateToString(Date date) {
        return dateFormat.format(date);
    }

    public static LocalDateTime dateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);

        return Date.from(zdt.toInstant());
    }

    /**
     * 传入LocalDateTime加上相应天数
     *
     * @param ldt  LocalDateTime时间
     * @param days 天数
     * @return
     */
    public static LocalDateTime localDateTimePlusDays(LocalDateTime ldt, int days) {
        return ldt.plus(days, ChronoUnit.DAYS);
    }

    /**
     * 传入LocalDateTime减去相应天数
     *
     * @param ldt  LocalDateTime时间
     * @param days 天数
     * @return
     */
    public static LocalDateTime localDateTimeMinusDays(LocalDateTime ldt, int days) {
        return ldt.minus(days, ChronoUnit.DAYS);
    }


    /**
     * 得到uuid
     * @return
     */
    public static String getUUID(){
        String uuid = UUID.randomUUID().toString(); //获取UUID并转化为String对象
        uuid = uuid.replace(TRANSVERSE_LINE, EMPTY);//因为UUID本身为32位只是生成时多了“-”，所以将它们去点就可
        return uuid;
    }

    /**
     * 设置文件下载响应信息
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param fileName
     */
    public static void setResponseHeader(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String fileName) {
        try {
            String agent = httpServletRequest.getHeader("USER-AGENT");
            if (agent != null) {
                agent = agent.toUpperCase();
                if (null == agent) {//中文文件名
                    fileName = new String(fileName.getBytes("UTF-8"), FileUtil.ISO);
                } else if (-1 != agent.indexOf(FileUtil.MSIE) || -1 != agent.indexOf(FileUtil.TRIDENT) || -1 != agent.indexOf(FileUtil.EDGE)) {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                } else {
                    fileName = new String(fileName.getBytes("UTF-8"), FileUtil.ISO);
                }
            }
            httpServletResponse.setContentType(FileUtil.CONTRNT_TYPE);
            httpServletResponse.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName);
        } catch (IOException e) {
            throw new ZjmsaOaException("io异常");
        }
    }

    /**
     * 通过反射得到字段值为1的字段名导出时使用
     * @param obj
     * @return
     */
    public static List<String> getFieldName(Object obj) {
        if (obj == null) return null;
        Field[] fields = obj.getClass().getDeclaredFields();
        List<String> list=new ArrayList<>();
        for (int j = 0; j < fields.length; j++) {
            fields[j].setAccessible(true);
//            // 字段名
//            System.out.print(fields[j].getName() + ",");
            // 字段值
            if (fields[j].getType().getName().equals(// String 类型
                    String.class.getName())) {
                try {
                    System.out.print(fields[j].get(obj));
                    if("1".equals(fields[j].get(obj))){
                        list.add(fields[j].getName());
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } else if (fields[j].getType().getName().equals(
                    Integer.class.getName())
                    || fields[j].getType().getName().equals("int")) {// int 类型
                try {
                    System.out.println(fields[j].getInt(obj));
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            // 其他类型。。。
        }
        return list;
    }

    public static void main(String[] args) {
        String sourceFilePath="D:\\1d7139d10d4a496bb0d2ed37abdc3911.doc";
        String newFilePath="D:\\test16.doc";
        copyFile(new File(sourceFilePath),new File(newFilePath));
    }

    /**
     * 拷贝文件
     * @param sourceFile
     * @param newFile
     */
    public static void copyFile(File sourceFile,File newFile){
        try {
            FileUtils.copyFile(sourceFile, newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将file文件转为byte数组
     * @param file
     */
    public static byte[] fileToByte(File file){
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len = -1;
            while((len = fis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
           return bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }




}
